<template>
  <div class="min-h-screen bg-black text-white">
    <!-- 顶部间距 -->
    <div class="w-full h-[55px] sm:h-[72px]"></div>

    <!-- 面包屑导航 -->
    <div class="max-w-full xl:px-2 lg:px-2 md:px-4 px-4 mt-6 mb-1 sm:mb-4">
      <div class="max-w-screen-2xl mx-auto">
        <nuxt-link
          :to="`${homepagePath}/`"
          class="justify-start text-white/60 text-base font-normal"
          >{{ t("common.breadcrumb.home") }}</nuxt-link
        >
        <span class="text-white/60 text-base font-normal px-2"> / </span>
        <nuxt-link
          :to="`${homepagePath}/careers`"
          class="text-white text-base font-normal"
          >{{ t("common.careers") }}</nuxt-link
        >
        <span class="text-white/60 text-base font-normal px-2"> / </span>
        <span class="text-white text-base font-normal">{{ job?.name }}</span>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <ErrorBoundary
      :error="pageError"
      :title="t('common.error')"
      :retry="true"
      :retry-text="t('common.retry')"
      @retry="handleRetry"
    >
      <div v-if="pending" class="flex justify-center py-12">
        <!-- 加载中 -->
        <div
          class="animate-spin h-8 w-8 border-4 border-cyan-400 rounded-full border-t-transparent"
        ></div>
      </div>

      <!-- 职位详情内容 -->
      <div v-else-if="job" class="container mx-auto pb-16">
        <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
          <!-- 主要内容 -->
          <div class="lg:col-span-3 space-y-8">
            <!-- 职位头部信息 -->
            <div
              class="bg-zinc-900/50 backdrop-blur-sm border border-zinc-700/30 rounded-2xl p-8"
            >
              <h1 class="text-3xl font-bold text-white mb-4">{{ job.name }}</h1>
              <div
                class="flex flex-wrap items-center gap-6 text-zinc-400 text-sm mb-4"
              >
                <span class="flex items-center">
                  <svg
                    class="w-4 h-4 mr-2"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"
                    ></path>
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"
                    ></path>
                  </svg>
                  {{ getLocationName(job.location) }}
                </span>
                <span class="flex items-center">
                  <svg
                    class="w-4 h-4 mr-2"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
                    ></path>
                  </svg>
                  {{ formatDate(job.createTime) }}
                </span>
              </div>
              <div class="text-xs text-zinc-500">
                ID: {{ job.id }} | {{ formatDate(job.updateTime) }}
                {{ t("careers.PositionCard.update") }}
              </div>
            </div>

            <!-- 工作职责 -->
            <div
              class="bg-zinc-900/50 backdrop-blur-sm border border-zinc-700/30 rounded-2xl p-8"
            >
              <h2
                class="text-white text-2xl font-semibold mb-6 flex items-center"
              >
                <svg
                  class="w-6 h-6 mr-3 text-[#35F1FF]"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                >
                  <rect x="4" y="2" width="16" height="20" rx="2" ry="2" />
                  <line x1="8" y1="9" x2="16" y2="9" />
                  <line x1="8" y1="13" x2="16" y2="13" />
                </svg>
                {{ t("careers.PositionCard.job") }}
              </h2>
              <div
                class="text-zinc-300 leading-relaxed whitespace-pre-line"
                v-html="job.jobResponsibilities"
              ></div>
            </div>

            <!-- 薪资福利 -->
            <div
              class="bg-zinc-900/50 backdrop-blur-sm border border-zinc-700/30 rounded-2xl p-8"
            >
              <h2
                class="text-white text-2xl font-semibold mb-6 flex items-center"
              >
                <svg
                  class="w-6 h-6 mr-3 text-[#35F1FF]"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                >
                  <path
                    d="M12 2v20M17 5H9.5a3.5 3.5 0 100 7h5a3.5 3.5 0 110 7H7"
                  ></path>
                </svg>
                {{ t("careers.PositionCard.CB") }}
              </h2>
              <div class="text-zinc-300 leading-relaxed whitespace-pre-line">
                {{ job.benefits }}
              </div>
            </div>

            <!-- 工作时间 -->
            <div
              class="bg-zinc-900/50 backdrop-blur-sm border border-zinc-700/30 rounded-2xl p-8"
            >
              <h2
                class="text-white text-2xl font-semibold mb-6 flex items-center"
              >
                <svg
                  class="w-6 h-6 mr-3 text-[#35F1FF]"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                >
                  <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
                  <line x1="16" y1="2" x2="16" y2="6"></line>
                  <line x1="8" y1="2" x2="8" y2="6"></line>
                  <line x1="3" y1="10" x2="21" y2="10"></line>
                </svg>
                {{ t("careers.PositionCard.workingHours") }}
              </h2>
              <div class="text-zinc-300 leading-relaxed whitespace-pre-line">
                {{ job.workTime }}
              </div>
            </div>
          </div>

          <!-- 侧边栏 - 申请信息 -->
          <div class="lg:col-span-1">
            <div class="sticky top-8">
              <div
                class="bg-zinc-900/50 backdrop-blur-sm border border-zinc-700/30 rounded-2xl p-6"
              >
                <div class="text-center mb-6">
                  <div
                    class="inline-flex items-center justify-center w-16 h-16 bg-[#35F1FF]/10 rounded-full mb-4"
                  >
                    <svg
                      class="w-8 h-8 text-[#35F1FF]"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
                      ></path>
                    </svg>
                  </div>
                  <h3 class="text-xl font-semibold text-white mb-2">
                    {{ t("careers.jobs.button") }}
                  </h3>
                </div>

                <!-- 邮箱信息 -->
                <div class="bg-zinc-800/30 rounded-xl p-4 mb-6">
                  <div class="text-sm text-zinc-400 mb-2">
                    {{ t("contact.email") }}
                  </div>
                  <div class="text-[#35F1FF] font-medium break-all mb-3">
                    {{ job.email }}
                  </div>
                  <button
                    @click="copyEmail"
                    class="w-full px-4 py-3 bg-[#35F1FF]/10 text-[#35F1FF] font-medium rounded-lg hover:bg-[#35F1FF]/20 transition-colors"
                  >
                    {{ copied ? t("common.copied") : t("common.copy") }}
                  </button>
                </div>

                <!-- 申请提示 -->
                <div class="text-xs text-zinc-500 text-center leading-relaxed">
                  {{ t("careers.jobs.sendTip") }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 未找到职位 -->
      <div v-else class="container mx-auto px-4 py-16 text-center">
        <div
          class="inline-flex items-center justify-center w-16 h-16 bg-zinc-800/30 rounded-full mb-4"
        >
          <svg
            class="w-8 h-8 text-zinc-400"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M21 13.255A23.931 23.931 0 0112 15c-3.183 0-6.22-.62-9-1.745M16 6V4a2 2 0 00-2-2h-4a2 2 0 00-2-2v2m8 0H8m8 0v2a2 2 0 002 2M8 6V4h8V6M8 6v2a2 2 0 002 2h4a2 2 0 002-2V6"
            ></path>
          </svg>
        </div>
        <p class="text-zinc-400 mb-4">{{ t("careers.notFound") }}</p>
        <NuxtLink
          to="/careers"
          class="inline-flex items-center px-4 py-2 bg-[#35F1FF]/10 text-[#35F1FF] rounded-lg hover:bg-[#35F1FF]/20 transition-colors"
        >
          {{ t("careers.backToList") }}
        </NuxtLink>
      </div>
    </ErrorBoundary>
  </div>
</template>

<script setup lang="ts">
import type { JobApiResponse, Job } from "~/data/jobs";
import { locationMap, workTypeMap } from "~/data/jobs";
import { useClipboard } from "@vueuse/core";

/**
 * 获取路由参数
 */
const route = useRoute();
const { t, locale } = useI18n();

// 计算首页路径
const homepagePath = computed(() => {
  return locale.value === "zh" ? "" : `/${locale.value}`;
});

// API配置
const apiUrl = computed(
  () =>
    `https://digital.sohomall.jp/prod-api/system/workInfo/noVerify/${route.params.id}`
);
const {
  data: apiResponse,
  pending,
  error: pageError,
  refresh: handleRetry,
} = await useFetch<JobApiResponse>(apiUrl, {});

// 从响应中获取职位信息
const job = computed<Job | null>(() => apiResponse.value?.data ?? null);

useHead(() => {
  const title = job.value
    ? `${job.value.name} - ${t("common.careers")} - Hanye`
    : t("careers.notFound");
  const description = job.value
    ? job.value.jobResponsibilities.substring(0, 150)
    : t("careers.notFoundDescription", "Could not find the job details.");

  return {
    title,
    meta: [{ name: "description", content: description }],
  };
});

/**
 * 获取地点名称
 * @param locationId 地点ID
 * @returns 地点名称
 */
const getLocationName = (locationId: number): string => {
  return (
    locationMap[locationId] || t("careers.unknownLocation", "Unknown Location")
  );
};

/**
 * 格式化日期
 * @param dateString 日期字符串
 * @returns 格式化后的日期
 */
const formatDate = (dateString?: string): string => {
  if (!dateString) return "";
  const date = new Date(dateString);
  // 使用 toLocaleDateString 以支持国际化
  return date.toLocaleDateString(locale.value, {
    year: "numeric",
    month: "long",
    day: "numeric",
  });
};

// 复制邮箱功能
const { copy, copied, isSupported } = useClipboard({
  source: computed(() => job.value?.email ?? ""),
  copiedDuring: 2000,
  legacy: true,
});

/**
 * 复制邮箱地址到剪贴板
 */
const copyEmail = async () => {
  if (!job.value?.email) return;

  if (!isSupported.value) {
    alert(
      t("common.copyNotSupported", "Copying is not supported in your browser.")
    );
    return;
  }

  try {
    await copy();
  } catch (err) {
    console.error("Failed to copy email: ", err);
    alert(t("common.copyFailed", "Failed to copy email."));
  }
};
</script>
